"""
工具函数
"""
from datetime import datetime
from typing import Any, Dict, Optional
import json

def serialize_datetime(obj: Any) -> Any:
    """序列化datetime对象"""
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")

def to_dict_safe(obj: Any) -> Dict[str, Any]:
    """安全转换为字典"""
    if hasattr(obj, '__dict__'):
        result = {}
        for key, value in obj.__dict__.items():
            if not key.startswith('_'):
                result[key] = value
        return result
    return {}

def safe_json_loads(json_str: str) -> Optional[Dict[str, Any]]:
    """安全的JSON解析"""
    try:
        return json.loads(json_str) if json_str else None
    except (json.JSONDecodeError, TypeError):
        return None

def safe_json_dumps(obj: Any) -> str:
    """安全的JSON序列化"""
    try:
        return json.dumps(obj, ensure_ascii=False, default=serialize_datetime)
    except (TypeError, ValueError):
        return "{}"